<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡面区域 -->
    <el-card>
      <!-- 搜索和增加区域 -->
      <el-row :gutter="20">
        <!-- 搜索框区域 -->
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUsersList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUsersList"
            ></el-button>
          </el-input>
        </el-col>
        <!-- 增加用户区域 -->
        <el-col :span="6">
          <el-button type="primary" @click="AddDialogVisible = true">
            增加用户
          </el-button>
        </el-col>
      </el-row>
      <!-- 用户显示区域 -->
      <el-table :data="userList" border style="width: 100%" stripe>
        <el-table-column type="index"> </el-table-column>
        <el-table-column prop="username" label="用户名" width="180">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="180">
        </el-table-column>
        <el-table-column prop="mobile" label="电话" width="180">
        </el-table-column>
        <el-table-column prop="role_name" label="角色" width="180">
        </el-table-column>
        <el-table-column label="状态" width="80">
          <!-- 状态内switch按钮 -->
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              @change="userStateChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <!-- 操作按钮区域 -->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 编辑 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editDialog(scope.row.id)"
            ></el-button>
            <!-- 删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="DeleteUser(scope.row.id)"
            ></el-button>
            <!-- 分配角色 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="assignRole(scope.row.id)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 底部分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2, 5, 8, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="toral"
      >
      </el-pagination>
    </el-card>

    <!-- 增加用户对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="AddDialogVisible"
      width="50%"
      @close="addDialogClose"
    >
      <!-- 表单信息 -->
      <el-form
        :model="AddFormList"
        :rules="AddFormRules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户" prop="username">
          <el-input v-model="AddFormList.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="AddFormList.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="AddFormList.email"></el-input>
        </el-form-item>
        <el-form-item label="电话号码" prop="mobile">
          <el-input v-model="AddFormList.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="AddDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser"> 确 定 </el-button>
      </span>
    </el-dialog>

    <!-- 编辑用户对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="closeEditForm"
    >
      <!-- 表单区域 -->
      <el-form
        :model="EditFormList"
        :rules="EditFormRules"
        ref="EditForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名">
          <el-input v-model="EditFormList.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="email">
          <el-input v-model="EditFormList.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="EditFormList.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="EditFormList.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="EditUserInfo"> 确 定 </el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="提示"
      :visible.sync="AssignRoleVisible"
      width="50%"
    >
      <!-- 表单信息 -->
      <el-form
        :model="AssignFormList"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户" prop="username">
          <el-input
            placeholder="请输入内容"
            v-model="AssignFormList.username"
            :disabled="true"
            class="role_input"
            >
          </el-input>
        </el-form-item>
        <el-form-item label="权限" >
          <el-select v-model="RoleSelectValue" placeholder="请选择" @change="RoleSelect()">
            <el-option
              v-for="item in this.RoleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="AssignRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="AssignRoleInfo()"> 确 定 </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "users",
  created() {
    // 生命周期开始时请求用户数据
    this.getUsersList();
  },
  data() {
    // 验证邮箱格式是否正确
    var checkEmail = (rule, value, callback) => {
      const regEmail =
        /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
      if (regEmail.test(value)) {
        callback();
      }
      callback(new Error("邮箱格式有误,请重新输入"));
    };
    // 验证电话格式是否正确
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/;
      if (regMobile.test(value)) {
        callback();
      }
      callback(new Error("手机格式不正确,请重新输入"));
    };
    return {
      // 提交网络请求所需要的参数
      queryInfo: {
        query: "",
        // 当前页数
        pagenum: 1,
        // 当前页数有多少个
        pagesize: 5,
      },
      // 从服务器获取到的用户数据
      userList: [],
      // 用户总数
      toral: 0,
      // 增加用户对话框是否显示
      AddDialogVisible: false,
      // 分配用户角色对话框是否提示
      AssignRoleVisible: false,
      // 增加用户输入表单时绑定的数据
      AddFormList: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      // 增加用户对话框的验证规则
      AddFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "长度在 6 到 15 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入电话号码", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      editDialogVisible: false,
      // 编辑表单时用户输入的数据绑定
      EditFormList: {},
      // 修改用户的验证规则
      EditFormRules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入电话号码", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      RoleOptions: [
        {
          value: 0,
          label: '超级管理员'
        },
        {
          value: 30,
          label: '测试角色'
        },
        {
          value: 300,
          label: '访客'
        }
      ],
      RoleSelectValue: '',
      AssignFormList: {}
    };
  },
  methods: {
    // 获取用户数据并渲染到表格上
    async getUsersList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo,
      });
      if (res.meta.status !== 200) {
        return this.$message.error("获取用户列表失败");
      }
      this.userList = res.data.users;
      this.toral = res.data.total;
    },
    // 变更每页个数时触发
    handleSizeChange(newPages) {
      this.queryInfo.pagesize = newPages;
      // 变更之后需要重新发起请求，不然页面不会变更
      this.getUsersList();
    },
    // 当前页变动时触发
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getUsersList();
    },
    // 监听状态栏变化，并提交到数据库
    async userStateChange(uesrInfo) {
      const { data: res } = await this.$http.put(
        `users/${uesrInfo.id}/state/${uesrInfo.mg_state}`
      );
      if (res.meta.status !== 200) {
        uesrInfo.mg_state = !uesrInfo.mg_state;
        this.$message.error("修改状态失败!");
      }
      this.$message.success("修改状态成功!");
    },
    // 添加用户对话框退出时重置信息
    addDialogClose() {
      this.$refs.ruleForm.resetFields();
    },
    // 添加用户
    addUser() {
      this.$refs.ruleForm.validate(async (validate) => {
        // eslint-disable-next-line no-useless-return
        if (!validate) return;
        const { data: res } = await this.$http.post("users", this.AddFormList);
        console.log(res);
        if (res.meta.status !== 201) {
          this.$message.error("添加用户失败!");
        } else {
          this.$message.success("添加用户成功!");
        }
        // 点击确定之后重置表单信息来
        this.AddDialogVisible = false;
        // 添加用户之后重新获取用户数据，更新页面数据
        this.getUsersList();
      });
    },
    // 通过用户id获取数据
    async editDialog(id) {
      const { data: res } = await this.$http.get(`users/${id}`);
      if (res.meta.status !== 200) this.$message.error("修改用户失败!");
      this.EditFormList = res.data;
      this.editDialogVisible = true;
    },
    // 关闭对话框重置表单
    closeEditForm() {
      this.$refs.EditForm.resetFields();
    },
    // 点击确定对表单进行与验证并提交数据
    EditUserInfo() {
      this.$refs.EditForm.validate(async (valid) => {
        // eslint-disable-next-line no-useless-return
        if (!valid) return;
        const { data: res } = await this.$http.put(
          `users/${this.EditFormList.id}`,
          { email: this.EditFormList.email, mobile: this.EditFormList.mobile }
        );
        if (res.meta.status !== 200) {
          this.$message.error("更新用户信息失败!");
        } else {
          this.$message.success("更新用户信息成功!");
        }
        // 对话框隐藏
        this.editDialogVisible = false;
        // 重新刷新页面数据
        this.getUsersList();
      });
    },
    // 删除用户
    async DeleteUser(id) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResult !== "confirm") {
        this.$message.info("已取消删除用户");
      } else {
        const { data: res } = await this.$http.delete(`users/${id}`);
        if (res.meta.status !== 200) {
          this.$message.error("删除用户失败");
        } else {
          // 重新获取数据
          this.getUsersList();
          this.$message.success("已成功删除用户");
        }
      }
    },
    async assignRole(id) {
      const { data: res } = await this.$http.get(`users/${id}`);
      if (res.meta.status !== 200) this.$message.error('获取用户数据失败！')
      this.AssignFormList = res.data
      this.AssignRoleVisible = true
    },
    RoleSelect() {
      this.AssignFormList.rid = this.RoleSelectValue
    },
    async AssignRoleInfo() {
      const { data: res } = await this.$http.put(`users/${this.AssignFormList.id}/${this.AssignFormList.rid}`);
      if (res.meta.status !== 200) {
        this.$message.error(`分配角色失败！状态为${res.meta.status}`)
      } else {
        this.$message.success('分配角色成功！')
      }
      this.AssignRoleVisible = false
    }
  },
};
</script>

<style lang="less" scoped>
.el-table {
  margin-top: 15px;
  font-size: 12px;
  font-family: Arial, Helvetica, sans-serif;
}
.role_input{
  width: 300px;
}
</style>
